package com.iplant.wms.serviceImpl.dao.pkg;

import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.po.bms.BMSEmployee;
import com.iplant.wms.service.po.pkg.MSSPackageRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class MSSPackageRuleDAO extends BaseDAO {

    private static MSSPackageRuleDAO Instance = null;
    private static Logger logger = LoggerFactory.getLogger(MSSPackageRuleDAO.class);

    private MSSPackageRuleDAO() {
        super();

        setTableName("mss_packagerule");
    }

    public static MSSPackageRuleDAO getInstance() {
        if (Instance == null)
            Instance = new MSSPackageRuleDAO();
        return Instance;
    }

    public void MSS_UpdatePackageRule(BMSEmployee wLoginUser, MSSPackageRule wPackageRule, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);

        try {
            if (wPackageRule == null || StringUtils.isEmpty(wPackageRule.Name)) {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }
            MSSPackageRule wPackageRuleO = this.MSS_CheckPackageRule(wLoginUser, wPackageRule, wErrorCode);
            if (wPackageRuleO.ID > 0) {
                wErrorCode.set(ExceptionTypes.Duplication.getValue());
            }
            if (wErrorCode.Result != 0)
                return;

            Map<String, Object> wParwms = new HashMap<String, Object>();

            wParwms.put("Name", wPackageRule.Name);
            wParwms.put("Code", wPackageRule.Code);
            wParwms.put("Description", wPackageRule.Description);

            wParwms.put("EditorID", wLoginUser.getID());
            wParwms.put("EditTime", Calendar.getInstance());


            if (wPackageRule.ID > 0) {
                wParwms.put("ID", wPackageRule.ID);
                super.Update(super.getTableName("mss_packagerule"), "ID", wParwms);
            } else {
                wParwms.put("CreatorID", wLoginUser.getID());
                wParwms.put("CreateTime", Calendar.getInstance());
                wParwms.put("Active", 0);
                wPackageRule.ID = super.Insert(super.getTableName("mss_packagerule"), wParwms);
                if (wPackageRule.ID > 0) {
                    MSSPackagePropDAO.getInstance().MSS_CreatePackageProp(wLoginUser, wPackageRule.ID, wErrorCode);
                }
            }

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_UpdatePackageRule", ex);
        }
    }

    public void MSS_DeletePackageRule(BMSEmployee wLoginUser, MSSPackageRule wPackageRule, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);

        try {
            if (wPackageRule == null || wPackageRule.ID <= 0) {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }
            int wRows = this.DeletePO(wLoginUser, wPackageRule, wErrorCode);

            if (wRows > 0) {
                MSSPackagePropDAO.getInstance().MSS_DeletePackageProp(wLoginUser, wPackageRule.ID, wErrorCode);
                MSSPackageRangeDAO.getInstance().MSS_DeletePackageRange(wLoginUser, wPackageRule.ID, wErrorCode);
            }

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_UpdatePackageRule", ex);
        }
    }


    public void MSS_ActivePackageRule(BMSEmployee wLoginUser, MSSPackageRule wPackageRule, int wActive,
                                    OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        // 判断客户信息是否存在(中国：统一社会信用代码，国外:提醒是否有重复）

        try {
            if (wPackageRule == null || wPackageRule.ID <= 0) {
                wErrorCode.set(ExceptionTypes.Parameter.getValue());
                return;
            }

            Map<String, Object> wParwms = new HashMap<String, Object>();

            wParwms.put("ID", wPackageRule.ID);
            wParwms.put("EditorID", wLoginUser.getID());
            wParwms.put("EditTime", Calendar.getInstance());
            wParwms.put("Active", wActive);
            super.Update(super.getTableName("mss_packagerule"), "ID", wParwms);

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_ActivePackageRule", ex);
        }
    }

    public List<MSSPackageRule> MSS_QueryPackageRuleList(
            BMSEmployee wLoginUser, String wName,
            int wActive,
            Pagination wPagination, OutResult<Integer> wErrorCode) {
        return this.MSS_QueryPackageRuleList(wLoginUser, -1, "", wName,
                wActive, wPagination, wErrorCode);
    }

    private List<MSSPackageRule> MSS_QueryPackageRuleList(
            BMSEmployee wLoginUser, int wID, String wCode, String wName,
            int wActive, Pagination wPagination, OutResult<Integer> wErrorCode) {
        List<MSSPackageRule> wMSSPackageRuleList = new ArrayList<MSSPackageRule>();
        wErrorCode.set(0);

        try {

            // Step02:查询
            Map<String, Object> wParwms = new HashMap<String, Object>();
            String wSQLText = "";
            wSQLText = StringUtils.Format(
                    "Select t.*,t3.Name as CreatorName ,t4.Name as EditorName  from {0}.mss_packagerule t  "

                            + " left join {0}.mbs_user t3 on t.CreatorID=t3.ID "
                            + " left join {0}.mbs_user t4 on t.EditorID=t4.ID "
                            + " where (:ID<=0 or  t.ID=:ID) and (:Code =''''  or  t.Code=:Code) "
                            + " AND (:Active<0 or  t.Active=:Active) AND (:Name = '''' or  t.Name like :Name) ",
                    super.getDBName());

            wSQLText = this.DMLChange(wSQLText);

            wParwms.put("ID", wID);
            wParwms.put("Code", wCode);
            wParwms.put("Active", wActive);
            wParwms.put("Name", StringUtils.isEmpty(wName) ? "" : ("%" + wName + "%"));

            wMSSPackageRuleList = super.QueryForList(wSQLText, wParwms, wPagination, MSSPackageRule.class);

            // Step03:配置系统
        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_QueryPackageRuleList", ex);
        }
        return wMSSPackageRuleList;
    }

    public MSSPackageRule MSS_QueryPackageRule(BMSEmployee wLoginUser, int wID, String wCode, OutResult<Integer> wErrorCode) {
        MSSPackageRule wResult = new MSSPackageRule();
        wErrorCode.set(0);

        try {
            List<MSSPackageRule> wList = null;
            if (wID > 0) {
                wList = this.MSS_QueryPackageRuleList(wLoginUser, wID, "", "", -1, Pagination.getDefault(), wErrorCode);

            } else if (StringUtils.isNotEmpty(wCode)) {
                wList = this.MSS_QueryPackageRuleList(wLoginUser, -1, wCode, "", -1, Pagination.getDefault(), wErrorCode);
            }
            if (wList != null && wList.size() > 0) {
                wResult = wList.get(0);
            }
        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_QueryPackageRuleByID", ex);
        }
        return wResult;
    }

    public MSSPackageRule MSS_CheckPackageRule(BMSEmployee wLoginUser, MSSPackageRule wMSSPackageRule, OutResult<Integer> wErrorCode) {
        MSSPackageRule wPackageRule = new MSSPackageRule();
        wErrorCode.set(0);

        try {

            // Step0:查询
            Map<String, Object> wParwms = new HashMap<String, Object>();
            String wSQLText = StringUtils.Format(
                    "Select * from {0}.mss_packagerule "
                            + " where ID!=:ID " +
                            "  AND ( Name =:Name or (:Code != '''' and Code=:Code) )",
                    super.getDBName());
            wParwms.clear();
            wParwms.put("ID", wMSSPackageRule.ID);
            wParwms.put("Name", wMSSPackageRule.Name);
            wParwms.put("Code", wMSSPackageRule.Code);

            wSQLText = this.DMLChange(wSQLText);
            List<Map<String, Object>> wQueryResultList = super.queryForList(wSQLText, wParwms);
            for (Map<String, Object> wSqlDataReader : wQueryResultList) {
                wPackageRule.ID = StringUtils.parseInt(wSqlDataReader.get("ID"));
                wPackageRule.Name = StringUtils.parseString(wSqlDataReader.get("Name"));
                wPackageRule.Code = StringUtils.parseString(wSqlDataReader.get("Code"));

                wPackageRule.CreatorID = StringUtils.parseInt(wSqlDataReader.get("CreatorID"));
                wPackageRule.CreateTime = StringUtils.parseCalendar(wSqlDataReader.get("CreateTime"));
                wPackageRule.EditorID = StringUtils.parseInt(wSqlDataReader.get("EditorID"));
                wPackageRule.EditTime = StringUtils.parseCalendar(wSqlDataReader.get("EditTime"));
                wPackageRule.Active = StringUtils.parseInt(wSqlDataReader.get("Active"));

            }

        } catch (Exception ex) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            logger.error("MSS_CheckPackageRule", ex);
        }
        return wPackageRule;
    }

}
